use([
    'public/javascripts/widget/select/select.js',
    'public/javascripts/widget/prompt/prompt.js'
]);
(function ($, window, document, undefined ){
    function use(config, callback){
        $.ajax({
            url: config.url,
            type: "get",
            dataType: 'html',
            async:false,
            success: function(data){
                if(config.type && config.type.toLowerCase() == 'css'){
                    var styleEle = document.createElement("style");
                    styleEle.innerHTML = data;
                    $('head')[0].appendChild(styleEle);
                }else if(config.type && config.type.toLowerCase() == 'html'){
                    $(config.append).html(data);
                }
            }
        })
    }
    function useHttp(param){
        return $.ajax({
            url: param.url,
            datatype: 'json',
            data:param.data,
            contentType:'application/json; charset=utf-8',
            type: param.type,
            cache: false,
            async: false
        }).responseText;
    }

    $.fn.uploadBox = function (param){
        use({
            url:'common/uploadFile/uploadFile.css',
            type:'css'
        });
        use({
            url:'common/uploadFile/uploadFile.html',
            type:'html',
            append:param.append
        });
        window.localStorage.setItem("uploadSuccessful",true);
        //非可编辑状态添加附件按钮隐藏
        if(!param.edit){ $(".addButton").hide();}

        //点击添加附件按钮显示添加对话框，清除对话框内容
        var fileTypeCode,fileTypes,
            fileNameRight = false,
            backResult = [],
            orderFileData = getOrderFile(),
            fileNameInp = $("#fileNameInp"),
            projectFile = $("#projectFile"),
            upload_fileType = $("#upload_fileType"),
            inputNameErrorVal = $("#inputNameErrorVal"),
            fileDescribeInp = $("#fileDescribeInp"),
            clickBtn = $("#clickBtn"),
            uploadBtn = $(".uploadBtn"),
            progress = $('#progress'),
            option = {'maxSize': 10 * 1024 * 1024},
            PromptComponentprompt = param.prompt,
            DialogComponent = param.dialog;

        //判断是否可以上传
        function checkUpload(flag){
            if(flag){
                fileNameInp.css("border", "none");
                uploadBtn.css("border", "1px solid #eb4b51");
                uploadBtn.css("background-color", "white");
                uploadBtn.css("color", "#eb4b51");
                uploadBtn.css("cursor", "pointer");
                projectFile.css("cursor", "pointer");
                projectFile.attr("disabled", false);
            }else{
                fileNameInp.css("border", "none");
                uploadBtn.css("background-color", "white");
                uploadBtn.css("border", "1px solid #ccc");
                uploadBtn.css("color", "#ccc");
                uploadBtn.css("cursor", "not-allowed");
                projectFile.css("cursor", "not-allowed");
                projectFile.attr("disabled", true);
            }
        }

        startUpload();
        function startUpload(){
            if(param.edit){
                fileTypes = getFileType();
                fileTypeCode = fileTypes.data[0].code;
                clickBtn.attr("disabled", true);
                clickBtn.css("background-color", "white");
                clickBtn.css("border-color", "#ccc");
                checkUpload(true);
                fileNameInp.val("");
                fileDescribeInp.val("");
                projectFile.val("");
                upload_fileType.val(fileTypes.data[0].name);
                $("#addDataTr").show();
            }else{
                $("#addDataTr").hide();
            }
        }

        //点击添加附件按钮显示添加对话框，清除对话框内容
        clickBtn.on("click", function(){
            fileTypes =getFileType();
            fileTypeCode = fileTypes.data[0].code;
            clickBtn.attr("disabled", true);
            checkUpload(true);
            fileNameInp.val("");
            projectFile.val("");
            upload_fileType.val(fileTypes.data[0].name);
            fileDescribeInp.val("");
            $("#addDataTr").show();
            //fileNameInp.focus();
        });

        //添加中获取文件类型
        upload_fileType.on("click", function() {
            PromptComponentprompt.init({}).close();
            Select.sharePool['upload_fileType'] = null;
            upload_fileType.unbind();
            selectFactory({
                data: getCurrentFileType(''),
                id: "upload_fileType",
                defaultText: '',
                isSaveInputVal:true,
                onSearchValueChange: function (attachEvent, data) {
                    var fileTypeValues = getCurrentFileType(data);
                    attachEvent.setData(fileTypeValues);
                },
                attrTextModel: function (name, data) {
                    fileTypeCode = getCodeByName(name, data);
                    upload_fileType.val(name);
                }
            }).open();
        });
        function getCurrentFileType(q){
            q = q ? q : '';
            var config = {
                q: q,
                orderStatus:param.orderStatus
            };
            var data = getFileType(config);
            return data;
        }
        function getCodeByName(name, data) {
            if(!data) {
                data = getFileType()
            }
            if(!name) {
                return;
            }
            data = data.data;
            for(var index = 0; index < data.length; index++) {
                var currentName = data[index].name;
                if($.trim(currentName) == $.trim(name) || $.trim(data[index].name) == $.trim(name)) {
                    return  data[index].code
                }
            }
            return "无匹配结果";
        }

        //附件数据遍历
        function forEachData(data){
            PromptComponentprompt.init({}).close();
            $("#tableContainerId tbody .add-data").remove();
            if(data && data.length > 0){
                backResult.splice(0,backResult.length);
                data.forEach(function(value,index){

                    if(!value.fileUrl && value.path){
                        value.fileUrl = value.path
                    }
                    if(!value.fileId && value.id){
                        value.fileId = value.id
                    }
                    if(!value.fileType && value.type){
                        value.fileType = value.type
                    }
                    var fCode,backData = {
                        code:value.code,
                        desciption:value.desciption,
                        fileName:value.fileName,
                        fileId:value.fileId,
                        orderNo:value.orderNo
                    };
                    backResult.push(backData);

                    if(value.fileRandomName){
                        var idx = value.fileRandomName.lastIndexOf('.');
                        fCode= value.fileRandomName.substring(idx + 1, value.fileRandomName.length).toUpperCase();
                    }
                    if(value.name){
                        var idx = value.name.lastIndexOf('.');
                        fCode= value.name.substring(idx + 1, value.name.length).toUpperCase();
                    }
                    if(fCode==='DOC' || fCode=='DOCX'){
                        value.type = 'application/msword'
                    }else if(fCode==='XLS' || fCode==='XLSX'){
                        value.type = 'application/vnd.ms-excel'
                    }else if(fCode === 'JPG' || fCode === 'JPEG' || fCode === 'PNG' || fCode === 'BMP' || fCode === 'TIFF'|| fCode === 'TIF') {
                        value.type = 'image';
                    }else if (fCode === 'PDF'){
                        value.type = 'pdf';
                    }
                    var html = '<tr class="add-data"><td><span class="textPreview"><img style="margin-right: 5px;" src="../../images/uploadFile.svg">'+value.fileName+'</span></td>'+
                        '<td>'+value.fileTypeName+'</td>'+
                        '<td>'+value.desciption+'</td>'+
                        '<td data-fileUrl="'+value.fileUrl+'" ' +
                        ' data-fileId="'+value.fileId+'" '+
                        ' data-fileType="'+value.fileType+'" '+
                        ' data-name="'+value.fileRandomName+'" '+'';
                    html += '<p style="margin-top: -6px">';
                    html +='<a href="'+value.fileUrl+'?filename='+value.fileRandomName+'" class="textDownload" download></a>';
                    if(param.edit && (value.orderStatus === param.orderStatus || (param.orderStatus == 'COMMITED' && value.orderStatus == 'DRAFT'))){
                        html +='<span class="textDelete" data-status="'+value.orderStatus+'" id=' + value.id + '></span></p></td></tr>';
                    }
                    $("#tableContainerId tbody #addDataTr").before(html);
                });
            }
        }
        forEachData(orderFileData);

        //鼠标移除名称输入框进行名称校验
        fileNameInp.on("blur", checkFN);
        function checkFN(){
            fileNameRight = false;
            var fileName = fileNameInp.val(),
                reg = /^([\w\u4E00-\u9FA5_\-\s]+)+$/;
            if(reg.test(fileName)){
                if(param.orderNo) {
                    checkFileName(fileName, function (res) {
                        if (!res.data) {
                            fileNameRight = true;
                            checkUpload(false);
                            return inputNameErrorVal.val('已有该文件名！');
                        }else{
                            inputNameErrorVal.val('');
                            checkUpload(true);
                        }
                    });
                }else{
                    inputNameErrorVal.val('');
                    checkUpload(true);
                }
            }else if(fileName){
                fileNameRight = true;
                checkUpload(false);
                return inputNameErrorVal.val('请输入中英文、数字、“-_”、空格');
            }else{
                inputNameErrorVal.val('');
                checkUpload(true);
            }
        }
        //点击上传附件进行文件上传
        projectFile.on('change', function(e){
            var fileName = fileNameInp.val().trim(),
                fileDescribe = fileDescribeInp.val(),
                fileTypeName = upload_fileType.val(),
                file = (e.srcElement || e.target).files[0],
                fileUrl,fileData,myXhr;

            projectFile.val("");
            if(fileNameRight){
                PromptComponentprompt.init({}).close();
                fileNameInp.focus();
                return;
            }
            if(!fileTypeName && !fileTypeCode){
                upload_fileType.focus();
                return PromptComponentprompt.init({
                    msg: "类型不能为空!",
                    type: "warning"
                }).show();
            }
            if(file == undefined){
                return false;
            }
            if (file.size > option.maxSize) {
                return PromptComponentprompt.init({
                    msg: '单个文件最大支持10M!',
                    type: 'warning'
                }).show();
            }
            if (file.size == 0) {
                return PromptComponentprompt.init({
                    msg: '文件不能为空！',
                    type: 'warning'
                }).show();
            }
            var nameIdx = file.name.lastIndexOf('.');
            var nameCode = file.name.substring(nameIdx + 1, file.name.length).toUpperCase();
            if( !(nameCode ==='DOC' || nameCode==='DOCX' || nameCode==='XLS' || nameCode==='XLSX' ||
                nameCode=== 'JPG' || nameCode=== 'JPEG' || nameCode=== 'PNG' || nameCode=== 'BMP' ||
                nameCode=== 'TIFF'|| nameCode=== 'TIF' || nameCode=== 'PDF')
            ){
                return PromptComponentprompt.init({
                    msg: '文件格式不支持！',
                    type: 'warning'
                }).show();
            }
            if(file.type.indexOf('image') != -1){
                fileUrl = '/api/v1/sys/files/upload/pic';
            }else{
                fileUrl = '/api/v1/sys/files/upload/file';
            }
            fileData = new FormData();
            fileData.append('file', file);
            progress.text("0%");
            $('progress').attr({value : 0 , max : 100});
            window.localStorage.setItem("uploadSuccessful",false);
            $.ajax({
                type:'POST',
                url:fileUrl,
                data: fileData,
                processData: false,
                contentType: false,
                xhr: function(){
                    uploadBtn.css("display", "none");
                    $(".proDiv").css("display", "block");
                    myXhr = $.ajaxSettings.xhr();
                    if(myXhr.upload){
                        myXhr.upload.addEventListener('progress',progressHandlingFunction, false);
                    }
                    return myXhr;
                },
                success:function(res){
                    clickBtn.attr("disabled", false);
                    projectFile.val("");
                    if(res.errorCode === 0 && progress.text() === "100.0%"){
                        uploadBtn.css("display", "block");
                        $(".proDiv").css("display", "none");
                        fileName ? fileName : fileName = res.data.name
                        res.data.fileName = fileName;
                        res.data.fileRandomName = res.data.name;
                        res.data.desciption = fileDescribe;
                        res.data.code = fileTypeCode;
                        res.data.fileTypeName = fileTypeName;
                        res.data.orderStatus = param.orderStatus;
                        res.data.orderNo = param.orderNo;
                        var resultRes,config= {
                            code:res.data.code,
                            fileId:res.data.id,
                            fileName:res.data.fileName,
                            desciption:res.data.desciption,
                            orderNo:res.data.orderNo
                        };
                        resultRes = res.data;
                        if(param.orderNo){
                            addOrderFile(JSON.stringify(config), function(rs){
                                if(rs.errorCode === 0){
                                    resultRes.id = rs.data.id;
                                    PromptComponentprompt.init({
                                        msg: '添加成功！',
                                        type: 'success'
                                    }).show();
                                    orderFileData.push(resultRes);
                                    forEachData(orderFileData);
                                }else{
                                    PromptComponentprompt.init({
                                        msg: rs.msg,
                                        type: 'warning'
                                    }).show();
                                }
                                window.localStorage.setItem("uploadSuccessful",true);
                            });
                        }else{
                            orderFileData.push(resultRes);
                            forEachData(orderFileData);
                            window.localStorage.setItem("uploadSuccessful",true);
                        }
                        startUpload()
                    }else{
                        PromptComponentprompt.init({
                            msg: res.msg,
                            type: "warning"
                        }).show();
                        startUpload();
                        window.localStorage.setItem("uploadSuccessful",true);
                    }
                }
            });
        });
        function progressHandlingFunction(e) {
            var loaded = e.loaded,total = e.total;
            for (var i=0 ; i < loaded ; i= i+10){
                $('progress').attr({value : i , max : total});
                var percent = i / total*100;
                progress.text(percent.toFixed(1)+ "%");
            }
        }
        //点击删除进行附件删除
        $("#tableContainerId tbody").delegate(".textDelete","click", function(e){
            var trIndex = $(this).parents('td').parent('tr').index();
            var currentStatus = $(this).attr('data-status');
            if(param.system ==='customer ' && currentStatus !== param.orderStatus){
                return PromptComponentprompt.init({
                    msg: "该附件在之前状态下上传，不能删除！",
                    type: "warning"
                }).show();
            }
            DialogComponent.init({
                'type':'delete',
                'msg':'确定删除？',
                'success': function () {
                    if(param.orderNo){
                        delOrderFile(e.target.id, function(res){
                            if(res.errorCode === 0){
                                orderFileData && orderFileData.splice(trIndex,1);
                                forEachData(orderFileData);
                                PromptComponentprompt.init({
                                    msg: res.msg,
                                    type: 'success'
                                }).show();
                            }else{
                                PromptComponentprompt.init({
                                    msg: res.msg,
                                    type: 'warning'
                                }).show();
                            }
                        });
                    }else{
                        orderFileData && orderFileData.splice(trIndex,1);
                        forEachData(orderFileData);
                        PromptComponentprompt.init({
                            msg: '删除成功！',
                            type: 'success'
                        }).show();
                    }
                }
            }).show();
        });
        //点击预览按钮进行图片预览
        $("#tableContainerId tbody").delegate(".textPreview","click", function(e){
            var trDom = $(this).parents('td').parents('tr');
            var tdDom = trDom.children('td').eq(3);
            var dataName = tdDom.attr('data-name'),
                dataFileUrl = tdDom.attr('data-fileUrl').toString(),
                dataFileId = tdDom.attr('data-fileId').toString(),
                dataFileType = tdDom.attr('data-fileType');

            var typeImageFlag,typePdfFlag,pictures = [];
            if(dataFileType.includes("image")){
                typeImageFlag = true;
                typePdfFlag=false
            }else if(dataFileType.includes("pdf")){
                typeImageFlag = false;
                typePdfFlag=true
            }else{
                return PromptComponentprompt.init({
                    msg: "该文件暂不支持预览！",
                    type: "warning"
                }).show();
            }
            var pictureCfg = {
                name:dataName,
                id:dataFileId,
                path:dataFileUrl,
                type:dataFileType,
                typeImage:typeImageFlag,
                typePdf:typePdfFlag
            };
            pictures.push(pictureCfg);
            $('#slides').picturePreview({pictureId : dataFileId}, pictures);
        });
        //点击图片直接进行图片预览
        $("#tableContainerId tbody").delegate(".imgFilePic","click", function(e){
            var tdDom = $(this).parents('td');
            var dataName = tdDom.attr('data-name'),
                dataFileUrl = tdDom.attr('data-fileUrl').toString(),
                dataFileId = tdDom.attr('data-fileId').toString(),
                dataFileType = tdDom.attr('data-fileType');
            var pictures = [];
            var pictureCfg = {
                name:dataName,
                id:dataFileId,
                path:dataFileUrl,
                type:dataFileType,
                typeImage:true,
                typePdf:false
            };
            pictures.push(pictureCfg);

            $('#slides').picturePreview({pictureId : dataFileId}, pictures);
        });

        //获取附件信息
        function getOrderFile(){
            var params = {
                url:param.getOrderFile.url,
                type: param.getOrderFile.type,
                data:param.getOrderFile.param
            };
            var orderFileDatas = JSON.parse(useHttp(params));
            return orderFileDatas.data
        }
        //获取文件类型调用接口
        function getFileType(config){
            config ? config : config = { q: '',orderStatus:param.orderStatus};
            var params = {
                url:param.orderFileType.url,
                type: param.orderFileType.type,
                data:config
            };
            var resultData = JSON.parse(useHttp(params));
            return resultData
        }
        //校验附件名称是否重复
        function checkFileName(name,callBack){
            var config={
                orderNo:param.ckeckFileName.param.orderNo,
                fileName:name
            };
            var params = {
                url:param.ckeckFileName.url,
                type:param.ckeckFileName.type,
                data:config
            };
            var res = useHttp(params);
            callBack(JSON.parse(res));
        }
        //删除附件接口调用
        function delOrderFile(id,callBack){
            if(param.orderNo) {
                param.delOrderFile.param.orderFileId = id;
            }
            var params = {
                url:'/api/v1/order/attaches/'+param.orderNo+'/'+id+'/delete',
                type: param.delOrderFile.type,
                data:JSON.stringify(param.delOrderFile.param)
            };
            var res =useHttp(params);
            callBack(JSON.parse(res));
        }
        //添加附件接口调用
        function addOrderFile(config,callBack){
            var params = {
                url:param.addOrderFile.url,
                type: param.addOrderFile.type,
                data:config
            };
            var res = useHttp(params);
            callBack(JSON.parse(res));
        }

        PromptComponentprompt.init({}).close();
        return backResult
    }
})(jQuery, window, document);